package com.ybt.heartratem.moudle.main;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.lifecycle.ViewModelProviders;

import com.google.gson.Gson;
import com.ybt.heartratem.R;
import com.ybt.heartratem.common.app.AppViewModelFactory;
import com.ybt.heartratem.common.app.CacheManager;
import com.ybt.heartratem.common.app.Injection;
import com.ybt.heartratem.common.app.MyApplication;
import com.ybt.heartratem.common.entity.TeacherInfo;
import com.ybt.heartratem.common.utils.ThreadManager;
import com.ybt.heartratem.databinding.ActivitySettingBinding;
import com.ybt.heartratem.moudle.MainActivity;
import com.ybt.heartratem.moudle.MainVM;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import me.goldze.mvvmhabit.base.AppManager;
import me.goldze.mvvmhabit.base.BaseActivity;
import me.goldze.mvvmhabit.http.DownLoadManager;
import me.goldze.mvvmhabit.http.download.ProgressCallBack;
import me.goldze.mvvmhabit.utils.JsonEasy;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.ToastUtils;
import me.goldze.mvvmhabit.utils.constant.Contact;
import me.tatarka.bindingcollectionadapter2.BR;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import z.hol.shellandroid.ShellAndroid;

/***
 * 设置UI
 */
public class SettingActivity extends BaseActivity<ActivitySettingBinding, MainVM> implements Handler.Callback {
    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    private TeacherInfo teacher;

    @Override
    public MainVM initViewModel() {
        AppViewModelFactory factory = AppViewModelFactory.getInstance(MyApplication.getInstance());
        return ViewModelProviders.of(this, factory).get(MainVM.class);
    }

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_setting;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public void initData() {
        super.initData();
        viewModel.getTeacherList();
        binding.piWeightEdt.setText(Injection.aasDataRe().getConfigInfo());
    }

    @Override
    public void initViewObservable() {
        super.initViewObservable();
        initEvent();
        binding.currentVersionTv.setText("版本:V" + Contact.getVersionName());
        viewModel.getTeacherListEvent.observe(this, list -> {
            List<String> array = new ArrayList<>();
            for (TeacherInfo info1 : list) {
                array.add(info1.getName());
            }
            ArrayAdapter<String> adapterPerson = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, array);
            adapterPerson.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            binding.jcPersonTypeSp.setAdapter(adapterPerson);
            teacher = list.get(0);
            MyApplication.teacher = teacher;
            Injection.aasDataRe().saveLoginUser(new Gson().toJson(teacher));
            binding.jcPersonTypeSp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view,
                                           int pos, long id) {
                    TextView tv = (TextView) view;
                    tv.setTextSize(24f);
                    tv.setText(list.get(pos).getName());
                    tv.setTextColor(getResources().getColor(R.color.login_text_hint_color));
                    teacher = list.get(pos);
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {
                }
            });
        });
    }

    private void initEvent() {
        binding.backIv.setOnClickListener(view -> {
            finish();
        });
        //系统更新
        binding.checkVersionTv.setOnClickListener(view1 -> {
            try {
                String url = "http://api.sztbhz.com/newSchoolOAMobileService/LiuYang—PadAI-Version.txt";
                Request request = new Request.Builder()
                        .url(url)
                        .get()
                        .build();
                OkHttpClient okHttpClient = new OkHttpClient();
                final okhttp3.Call call = okHttpClient.newCall(request);
                ThreadManager.getNormalPool().execute(() -> {
                    try {
                        okhttp3.Response response = call.execute();
                        String responseResult = response.body().string().replaceAll("\\n|\\s*", "");
                        int version = Integer.parseInt(JsonEasy.getString(responseResult, "version"));
                        String versionUrl = JsonEasy.getString(responseResult, "url");
                        if (version > Contact.getVersionCode()) {
                            DownLoadManager.getInstance().load(versionUrl, new ProgressCallBack(CacheManager.SD_APK_DIR, "LiuYang—PadAI-Version.apk") {
                                @Override
                                public void onSuccess(Object o) {
                                    File file = new File(CacheManager.SD_APK_DIR + File.separator + "LiuYang—PadAI-Version.apk");
                                    ShellAndroid mShell = new ShellAndroid(null);
                                    String flagFile = mShell.initFlagMinimum(mContext);
                                    mShell.printOutput();
                                    mShell.setFlagFile(flagFile);
                                    mShell.checkRoot();
                                    mShell.exec(true, "pm install -r " + file.getAbsolutePath());
                                    KLog.e("ApkInstall", "执行安装文件：" + file.getAbsolutePath());
                                }

                                @Override
                                public void progress(long progress, long total) {
                                }

                                @Override
                                public void onError(Throwable e) {

                                }
                            });
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        //切换学校
        binding.changeSchoolTv.setOnClickListener(view -> {
            AppManager.getAppManager().finishElseAllActivity(SettingActivity.class);
            Injection.aasDataRe().saveUserName(null);
            Injection.aasDataRe().saveIsQueryLocalDB("ShiChiTime", true);//试吃时间默认可以更改
            Injection.aasDataRe().saveIsQueryLocalDB("ShiChiPic", true);//试吃照片默认强制上传
            startActivity(BindDeviceActivity.class);
            finish();
        });

        //切换厨师
        binding.changeTeacherTv.setOnClickListener(view -> {
            //保存当前操作PAD的厨师信息
            Injection.aasDataRe().saveLoginUser(new Gson().toJson(teacher));
            MyApplication.teacher = teacher;
            AppManager.getAppManager().finishElseAllActivity(SettingActivity.class);
            startActivity(MainActivity.class);
            finish();
        });

        //保存皮重
        binding.saveWeightTv.setOnClickListener(view -> {
            if (TextUtils.isEmpty(binding.piWeightEdt.getText().toString())) {
                ToastUtils.showLong("请输入留样盒的皮重");
                return;
            }
            Injection.aasDataRe().saveConfigInfo(binding.piWeightEdt.getText().toString());
        });
    }


    @SuppressLint("RestrictedApi")
    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    public boolean handleMessage(@NonNull Message msg) {
        return false;
    }
}